import cv2

# 创建VideoWriter为写多媒体文件
fourcc = cv2.VideoWriter_fourcc(*'XVID')  # 定义编码器
vw = cv2.VideoWriter('demo_output.avi', fourcc, 20.0, (1280, 720))

# 创建窗口
cv2.namedWindow('video', cv2.WINDOW_NORMAL)
cv2.resizeWindow('video', 640, 360)

# 获取视频设备 摄像头
cap = cv2.VideoCapture(0)
# 从视频文件中读取视频针
# cap = cv2.VideoCapture("img/test.mp4")
while (cap.isOpened()):
    # 从摄像头读取视频针
    ret, frame = cap.read()
    if ret == True:
        # 将视频针在窗口显示
        cv2.imshow('video', frame)
        cv2.resizeWindow('video', 640, 360)
        # 写数据到多媒体文件
        vw.write(frame)
        # 等待键盘事件

        key = cv2.waitKey(1)
        if (key & 0xFF == ord('q')):
            break
    else:
        break


# 释放videoCapture
cap.release()

# 释放videoWriter
vw.release()
# 释放窗口资源
cv2.destroyAllWindows()
